/**
 * This class acts as control message UDP server for the 
 * coordinator. This is used by ElectionSubSystem and 
 * FailureDetector. 
 */
package com.comp6231.coordinator;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author Farzana Alam
 * 
 */
public class ControlUDPServer extends Thread {

	// the port where the server will listen
	private int port;

	// Coordinator object
	private Coordinator coordinator;

	/**
	 * @param stationServer
	 * @param port
	 */
	public ControlUDPServer(Coordinator coordinatorObject, int port) {
		this.port = port;
		this.coordinator = coordinatorObject;
	}

	@Override
	public void run() {

		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket(port);
			byte[] buffer = new byte[1000];
			System.out.println("UDP server for control channel @"
					+ coordinator.myReplicaName + " is running on: " + port);
			while (true) {
				DatagramPacket request = new DatagramPacket(buffer,
						buffer.length);
				socket.receive(request);

				DatagramPacket reply = null;

				if (new String(request.getData()).trim().startsWith(
						"Are you alive?")) {
					String aliveMessage = "I am alive!";
					reply = new DatagramPacket(aliveMessage.toLowerCase()
							.getBytes(), aliveMessage.length(),
							request.getAddress(), request.getPort());
				} else if (new String(request.getData()).trim().startsWith(
						"Elect")) {
					String electMessage = "ElectReply ## "
							+ coordinator.myReplicaName + " ## "
							+ coordinator.myReplicaID;
					reply = new DatagramPacket(electMessage.toLowerCase()
							.getBytes(), electMessage.length(),
							request.getAddress(), request.getPort());
				}
				socket.send(reply);

			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (socket != null)
				socket.close();
		}

	}
}
